package com.wannengbang.cloudleader;

import android.annotation.SuppressLint;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.PowerManager;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import com.alibaba.idst.nui.NativeNui;
import com.alibaba.sdk.android.push.MessageReceiver;
import com.alibaba.sdk.android.push.notification.CPushMessage;
import com.wannengbang.cloudleader.a_main.MainActivity;
import com.wannengbang.cloudleader.bean.AliPushBean;
import com.wannengbang.cloudleader.login.LoginActivity;
import com.wannengbang.cloudleader.utils.SPManager;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.Map;

import static android.content.Context.KEYGUARD_SERVICE;
import static android.content.Context.NOTIFICATION_SERVICE;

public class AliPushReceiver extends MessageReceiver {

    // 消息接收部分的LOG_TAG
    public static final String REC_TAG = "AliPushReceiver";

    @Override
    public void onNotification(Context context, String title, String summary, Map<String, String> extraMap) {
        // TODO 处理推送通知
        Log.e(REC_TAG, "Receive notification, title: " + title + ", summary: " + summary + ", extraMap: " + extraMap);
    }

    @Override
    public void onMessage(Context context, CPushMessage cPushMessage) {
        Log.e(REC_TAG, "onMessage, messageId: " + cPushMessage.getMessageId() + ", title: " + cPushMessage.getTitle() + ", content:" + cPushMessage.getContent());
        if (!TextUtils.isEmpty(SPManager.getInstance().getToken()) && !TextUtils.isEmpty(SPManager.getInstance().getUserInfoJson())) {
            String contentText = "";
            String type = "";
            try {
                JSONObject jsonObject = new JSONObject(cPushMessage.getContent());
                type = jsonObject.getString("type");
                //推送+播报
                if ("1".equals(type)) {
                    contentText = jsonObject.getString("data");
                }
                //推送
                if ("2".equals(type)) {
                    contentText = jsonObject.getString("data");
                }
                if (!TextUtils.isEmpty(contentText)) {
                    EventBus.getDefault().post(new AliPushBean());
                    processCustomMessage(context, contentText);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            if ("true".equals(SPManager.getInstance().getSpeechSwitch())) {
                if (!TextUtils.isEmpty(contentText) && "1".equals(type)) {
                    startSynthesizer(contentText);
                }
            }
        }
    }

    @Override
    public void onNotificationOpened(Context context, String title, String summary, String extraMap) {
        Log.e(REC_TAG, "onNotificationOpened, title: " + title + ", summary: " + summary + ", extraMap:" + extraMap);
    }

    @Override
    protected void onNotificationClickedWithNoAction(Context context, String title, String summary, String extraMap) {
        Log.e(REC_TAG, "onNotificationClickedWithNoAction, title: " + title + ", summary: " + summary + ", extraMap:" + extraMap);
    }

    @Override
    protected void onNotificationReceivedInApp(Context context, String title, String summary, Map<String, String> extraMap, int openType, String openActivity, String openUrl) {
        Log.e(REC_TAG, "onNotificationReceivedInApp, title: " + title + ", summary: " + summary + ", extraMap:" + extraMap + ", openType:" + openType + ", openActivity:" + openActivity + ", openUrl:" + openUrl);
    }

    @Override
    protected void onNotificationRemoved(Context context, String messageId) {
        Log.e(REC_TAG, "onNotificationRemoved");
    }

    public void startSynthesizer(String ttsText) {
        NativeNui.GetInstance().startTts("1", "", ttsText);
    }


    /**
     * 处理自定义通知
     *
     * @param context
     */
    private void processCustomMessage(Context context, String contentText) {
        //显示不重复通知
        int requestCode = (int) System.currentTimeMillis();
        String channelID = "1";
        String channelName = "云创共享";
        String description = "通知";

        Intent intent = null;
        // 跳转的Activity
        if (!TextUtils.isEmpty(SPManager.getInstance().getToken()) && !TextUtils.isEmpty(SPManager.getInstance().getUserInfoJson())) {
            intent = new Intent(context, MainActivity.class);
        } else {
            intent = new Intent(context, LoginActivity.class);
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);


        NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
        if (notificationManager == null) {
            return;
        }

        //适配安卓8.0的消息渠道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel mChannel = new NotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_HIGH);
            // 配置通知渠道的属性
            mChannel.setDescription(description);
            // 设置通知出现时的闪灯（如果 android 设备支持的话）
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.RED);
            // 设置通知出现时的震动（如果 android 设备支持的话）
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            //最后在notificationmanager中创建该通知渠道
            notificationManager.createNotificationChannel(mChannel);
        }

        NotificationCompat.Builder notification = new NotificationCompat.Builder(context, channelID);

        notification.setAutoCancel(true)//点击后消失
                .setWhen(System.currentTimeMillis())
                .setContentTitle("云创共享")
                .setContentText(contentText)
                .setDefaults(Notification.DEFAULT_ALL)
                .setVibrate(new long[]{0, 300, 300, 300})
                .setContentIntent(pendingIntent)
                .setSmallIcon(R.mipmap.ic_launcher);

        notificationManager.notify(requestCode, notification.build());
        if ("true".equals(SPManager.getInstance().getSpeechSwitch())) {
            wakeUpAndUnlock();
        }
    }

    /**
     * 唤醒手机屏幕并解锁
     */
    public static void wakeUpAndUnlock() {
        // 获取电源管理器对象
        PowerManager pm = (PowerManager) MyApplication.getContext()
                .getSystemService(Context.POWER_SERVICE);
        boolean screenOn = pm.isScreenOn();
        if (!screenOn) {
            // 获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag
            @SuppressLint("InvalidWakeLockTag")
            PowerManager.WakeLock wl = pm.newWakeLock(
                    PowerManager.ACQUIRE_CAUSES_WAKEUP |
                            PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");
            wl.acquire(10000); // 点亮屏幕
            wl.release(); // 释放
        }
        // 屏幕解锁
        KeyguardManager keyguardManager = (KeyguardManager) MyApplication.getContext().getSystemService(KEYGUARD_SERVICE);
        KeyguardManager.KeyguardLock keyguardLock = keyguardManager.newKeyguardLock("unLock");
        // 屏幕锁定
        keyguardLock.reenableKeyguard();
        keyguardLock.disableKeyguard(); // 解锁
    }
}